package com.captain.special.二叉树.中等;

import com.captain.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/20 17:25
 */
public class 在二叉树中增加一行623 {
    public static void main(String[] args) {
        new 在二叉树中增加一行623().addOneRow(TreeNode.spanningTree(new Integer[]{4, 2, null, 3, 1}), 1, 3);
    }

    int layers = 1;
    Deque<TreeNode> queue = new LinkedList<>();
    int cDepth;
    int treeVal;
    boolean find;

    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        cDepth = depth;
        treeVal = val;
        if (depth == 1) {
            TreeNode node = new TreeNode(val);
            node.left = root;
            return node;
        }
        queue.add(root);
        recur();
        return root;
    }

    public void recur() {
        while (!queue.isEmpty()) {
            if (find) {
                break;
            }
            int size = queue.size();
            int curDepth = cDepth - 1;
            for (int i = 0; i < size; i++) {
                TreeNode pop = queue.pop();
                if (curDepth != layers) {
                    if (pop.left != null) {
                        queue.add(pop.left);
                    }
                    if (pop.right != null) {
                        queue.add(pop.right);
                    }
                    continue;
                }
                TreeNode newTreeNodeL = new TreeNode(treeVal);
                TreeNode newTreeNodeR = new TreeNode(treeVal);
                //如果说相等
                TreeNode orLeft = null;
                TreeNode orRight = null;
                if (pop.left != null) {
                    orLeft = pop.left;
                }
                if (pop.right != null) {
                    orRight = pop.right;
                }
                pop.left = newTreeNodeL;
                pop.right = newTreeNodeR;
                if (orLeft != null) {
                    newTreeNodeL.left = orLeft;
                }
                if (orRight != null) {
                    newTreeNodeR.right = orRight;
                }
                find = true;
            }
            layers++;
        }
    }
}
